package com.metaaps.eoraster;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import java.util.logging.Level;
import java.util.logging.Logger;

public class EOImageReaderFactory {

	public final static List<String> FORMATS = new ArrayList<String>();

	static {
		String[] temp = java.util.ResourceBundle.getBundle("eoraster").getString("formats").split(",");
		for (String f : temp) {
			FORMATS.add(f);
		}
	}

	/**
	 * this is the main entry point to create an image from a file source. All
	 * readers should be registered in the FORMATS static variables to be taken
	 * in account
	 * 
	 * @param file
	 *            the image file to be read as a GeoImageReader
	 * @return
	 */
	public static EOImageReader create(String file) {
		for (String format : FORMATS) {
			EOImageReader eoir = create(file, format);
			if (eoir != null) {
				return eoir;
			}
		}
		return null;
	}

	public static EOImageReader create(String file, String format) {

		Thread currentThread = Thread.currentThread();
		ClassLoader oldLoader = currentThread.getContextClassLoader();
		try {
			currentThread.setContextClassLoader(EOImageReader.class.getClassLoader());
			Class<?> clazz = EOImageReader.class.getClassLoader().loadClass(format);
			EOImageReader eoir = (EOImageReader) clazz.newInstance();
			eoir.setFile(new File(file));
			if (eoir.initialise()) {
				Logger.getLogger(EOImageReaderFactory.class.getName()).log(Level.INFO,
						"Successfully reading " + file + " as " + format+ "...");
				return eoir;
			}
		} catch (Exception ex) {
			Logger.getLogger(EOImageReaderFactory.class.getName()).log(Level.SEVERE, "Class " + format + " not found.", ex);
		} finally {
			currentThread.setContextClassLoader(oldLoader);

		}
		return null;
	}
}
